package iss;
import iss.list.MyList;
import iss.list.Node;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;




/**
 * Created by us on 2016/10/6.
 */
/**
 *inheritance thread and rewrite run()
 * */



public class Main_A {
    public static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        MyList list_a = new MyList();
        list_a.insert(list_a.getHead(),5);
        list_a.insert(list_a.getHead(),4);
        list_a.insert(list_a.getHead(),3);
        list_a.insert(list_a.getHead(),2);
        list_a.insert(list_a.getHead(),1);

        //create a new thread
    Thread ta = new Thread(){
        @Override
        public void run() {
            Node n = list_a.getHead();
            for (int i = 0; i < 3; ++i) {

                lock.lock();

                    try {
                        int k = n.getData();
                        k++;
                        n.setData(k);
                    } finally {
                        lock.unlock();
                    }
                    System.out.println("output the data now:"+n.getData());


                }

        }


    };

    //the other thread
      Thread tb = new Thread(){
            @Override
            public void run(){
               Node n = list_a.getHead();
                for(int i = 0; i<3;++i) {
                    lock.lock();


                        try {

                            int k = n.getData();
                            k--;
                            n.setData(k);

                        } finally {
                            lock.unlock();
                        }
                        System.out.println("output the data now:"+n.getData());

                    }
                }

        };

        ta.start();
        tb.start();

        Thread.sleep(10000);
       // System.out.printf("Final result of x = %d\n",Data);

        System.out.println("遍历检查：");
        //遍历检查
        for (Node n = list_a.getHead().getNext(); n!=list_a.getTail(); n=n.getNext()) {
            System.out.printf("%d ", n.getData());
        }
        System.out.println();


        //反向遍历 Traverse from tail to head, exclude tail and head.
        for (Node n = list_a.getTail().getPrev(); n!=list_a.getHead(); n=n.getPrev()) {
            System.out.printf("%d ", n.getData());
        }
        System.out.println();
  }
}
